package org.bling.star.common.connect;

import org.bling.star.common.response.BaseResponse;
import io.netty.channel.*;
import io.netty.util.concurrent.Promise;
import org.slf4j.Logger;

public abstract class AbstractConnectClient implements ConnectClient{

    private static final Logger log = org.slf4j.LoggerFactory.getLogger(AbstractConnectClient.class);

    protected Promise send0(Object message) {
        Channel channel = channel();
        Promise<BaseResponse> promise = channel.eventLoop().newPromise();
        try {
            ChannelFuture writeFuture = channel.writeAndFlush(message);
            // 创建一个Promise
            // 添加一个ChannelFutureListener来处理响应
            writeFuture.addListener((ChannelFutureListener) future -> {
                if (future.isSuccess()) {
                    log.info("发送消息：{},channel:{}", message,channel.remoteAddress());
                    // 请求发送成功，现在等待响应
                    channel.pipeline().addLast(new SimpleChannelInboundHandler<Object>() {
                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                            // 这里是接收到的响应
                            log.info("getMessage:{}",msg.toString());
                            BaseResponse response = (BaseResponse) msg;
                            // 将结果设置到Promise中
                            promise.setSuccess(response);
                            // 移除处理器，防止重复处理
                            ctx.pipeline().remove(this);
                        }
                    });
                } else {
                    // 请求发送失败，将失败原因设置到Promise中
                    promise.setFailure(future.cause());
                    log.info("发送消息失败：{},channel:{}", message);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
        return promise;
    }


    @Override
    public Boolean isShutdown() {
        return status() == ConnectStatus.SHUTDOWN;
    }
}
